/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.cheln.support.manager;

import android.content.Context;
import android.content.Intent;

import com.direction.hold.ui.CommonActivity;
import com.direction.hold.ui.SlideActivity;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import cn.cheln.explorer.config.Constants;
import cn.cheln.explorer.ds.scan.ScanService;
import cn.cheln.support.manager.listener.HomeListener;
import cn.cheln.support.data.text.xml.SPUtil;

/**
 * 
 * @author Administrator
 */
public class ActivityPool {

	public Map<Class, CommonActivity> activityMap = new HashMap<Class, CommonActivity>();
	private static ActivityPool instance;

	protected ActivityPool() {
	}

	public static ActivityPool getInstance() {
		if (null == instance) {
			instance = new ActivityPool();
		}
		return instance;
	}

	// 添加Activity到容器中

	public void addActivity(CommonActivity activity) {
		if (!activityMap.containsValue(activity)) {
			activityMap.put(activity.getClass(), activity);
		}
	}

	public void rmActivity(CommonActivity activity) {
		if (activityMap.containsKey(activity.getClass())) {
			activityMap.remove(activity.getClass());
		}
	}

	public void refresh() {
		refresh(null);
	}

	public void sortrefresh() {
		sortrefresh(null);
	}

	public void refresh(CommonActivity commonActivity) {
        for (Class activity : activityMap.keySet()) {
            if (commonActivity==null||activity != commonActivity.getClass()) {
            	activityMap.get(activity).refresh();
            }
        }
    }

	public void sortrefresh(CommonActivity commonActivity) {
		for (Class activity : activityMap.keySet()) {
			if (commonActivity == null || activity != commonActivity.getClass()) {
				activityMap.get(activity).sort();
			}
		}
	}

//	public void invokeMethod(String methodName, CommonActivity exclude,
//			Class[] classes, Object[] values) {
//		for (Class activity : activityMap.keySet()) {
//			if (activity != exclude.getClass()) {
//				try {
//					activity.getMethod(methodName, classes).invoke(activity,
//							values);
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
//			}
//		}
//	}

	public void exit() {
		// PackageInstallManager.getInstance().postJobWhenExiting(R.string.install_stoped_by_app_exit);
		SPUtil.putValue(SlideActivity.fileActivityInstance,
                Constants.SharedPrefernce.RememberedCategory,
                Constants.SharedPrefernce.KEY_CATEGORY, "");
		SlideActivity.fileActivityInstance.stopService(new Intent(
				((Context) SlideActivity.fileActivityInstance),
				ScanService.class));
		Set<CommonActivity> set = new HashSet(activityMap.values());
		for (CommonActivity activity : set) {
			activity.finish();
		}
		set.clear();
		set = null;
        HomeListener.stopInstall();
		System.exit(0);
	}
}
